#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Project: spd-sxmcc
"""
@author: lyndon
@time Created on 2019/2/23 16:54
@desc open pool of mysql
"""

from impala.error import HiveServer2Error
from impala.dbapi import connect
from DBUtils.PooledDB import PooledDB

from bratislava.conf.settings import hive_url
from bratislava.db import getconninfo2


class OPHive(object):
    __pool = None

    def __init__(self):
        # 构造函数，创建数据库连接、游标
        self.coon = OPHive.get_conn()
        self.cur = self.coon.cursor()

    # 数据库连接池连接
    @staticmethod
    def get_conn():
        if OPHive.__pool is None:
            print(hive_url)
            mysqlInfo = getconninfo2(hive_url)
            print(mysqlInfo)
            __pool = PooledDB(creator=connect, mincached=1, maxcached=20, host=mysqlInfo['host'],
                              port=mysqlInfo['port'], database=mysqlInfo['database'],
                              auth_mechanism=mysqlInfo['query']['auth_mechanism'],
                              kerberos_service_name=mysqlInfo['dbtype'])
            print(__pool)
        return __pool.connection()

    # 插入\更新\删除sql
    def op_insert(self, sql):
        ret = False
        try:
            self.cur.execute(sql)
            results = self.cur.status()
            if results == 'FINISHED_STATE':
                ret = True
                self.coon.commit()
            else:
                ret = False
                self.coon.rollback()
        except Exception as e:
            pass
        return ret

    # 查询单行
    def op_select_one(self, sql):
        # print('op_select', sql)
        self.cur.execute(sql)  # 执行sql
        select_res = self.cur.fetchone()  # 返回结果为字典
        # print('op_select', select_res)
        return select_res

    # 查询多行
    def op_select_all(self, sql):
        # print('op_select', sql)
        self.cur.execute(sql)  # 执行sql
        select_res = self.cur.fetchall()  # 返回结果为字典
        # print('op_select', select_res)
        return select_res

    # create drop
    def execsql(self, sql):
        """
        执行增删改操作
        :param sql:
        :return:
        """
        try:
            self.cur.execute(sql)
            # 得到执行语句的状态
            status = self.cur.status()
            if status == 'FINISHED_STATE':
                self.coon.commit()
            else:
                self.coon.rollback()
        except Exception as e:
            status = False
        return status


    def isHiveTableExists(self, tablename, databasename):
        """
        获取表是否存在
        :param table_name:
        :return: boolean
        """
        return self.cur.table_exists(tablename, databasename)

    # 释放资源
    def dispose(self):
        self.coon.close()
        # self.cur.close()


# 创建hive数据库连接池
oph = OPHive()

if __name__ == '__main__':
    res = oph.op_select_all('select 1')
    print(res)
